package com.gzyj.server.service;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.gzyj.data.common.VehicleIncrement;
import com.gzyj.server.config.LogConfig;
import com.gzyj.server.mapper.AnbiaoVehicleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class CommonService {

    @Value("${is.primary.gateway}")
    private Boolean primaryGateway;

    @Resource(name = "clusterRedisTemplate")
    private RedisTemplate<String, Object> clusterRedisTemplate;
    @Autowired
    private AnbiaoVehicleMapper anbiaoVehicleMapper;

    @Value("${redis.key.vehicle.info}")
    private String RedisKey_VehicleInfo;

    @PostConstruct
    public void init(){
        if(!primaryGateway) return;
        List<VehicleIncrement> vehicleIncrements = anbiaoVehicleMapper.selectVehicleAll(null, null);


        if (vehicleIncrements.size() > 0) {

            Set<String> keys3 = clusterRedisTemplate.keys(RedisKey_VehicleInfo + "*");

            if (CollectionUtil.isNotEmpty(keys3)) {
                for (String key : keys3) {

                    clusterRedisTemplate.delete(key);

                }
            }

            for (VehicleIncrement vehicleIncrement : vehicleIncrements) {

                clusterRedisTemplate.opsForValue().set(RedisKey_VehicleInfo + vehicleIncrement.getZongduanid() + ":" + vehicleIncrement.getId() + ":" + vehicleIncrement.getCheliangpaizhao() + vehicleIncrement.getChepaiyanse() + ":" + vehicleIncrement.getPlatformconnectiontype(), vehicleIncrement);

            }

            LogConfig.gpsAlarmLog.info("车辆信息加载完毕");
        }
    }

    private Set<String> getKeys(String pattern){

        return clusterRedisTemplate.execute(new RedisCallback<Set<String>>() {
            @Override
            public Set<String> doInRedis(RedisConnection connection) throws DataAccessException {
                Set<String> binaryKeys = new HashSet<>();

                Cursor<byte[]> cursor = connection.scan( ScanOptions.scanOptions().match(pattern).count(5000).build());
                while (cursor.hasNext()) {
                    binaryKeys.add(new String(cursor.next()));
                }
                return binaryKeys;
            }
        });

    }

    public VehicleIncrement getVehInfo(String simnum) {
        Set<String> keys = getKeys(RedisKey_VehicleInfo + simnum + ":*:*:1");
        VehicleIncrement vehicleInfo = null;
        if (CollectionUtil.isNotEmpty(keys)) {
            Object obj = clusterRedisTemplate.opsForValue().get(new ArrayList<String>(keys).get(0));
            if (obj == null) {
                return null;
            } else {
                vehicleInfo = JSONObject.parseObject(JSON.toJSONString(obj, SerializerFeature.DisableCircularReferenceDetect), VehicleIncrement.class);
            }
        } else {
            return null;
        }
        return vehicleInfo;
    }

}
